﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Html;
using Windows.Web.Syndication;

namespace RssReader
{
    public class SyndicationHelper
    {
        LocalSettings localSettings = new LocalSettings();
        private string urlKey = "url";

        public async Task<List<Item>> Get_feed()
        {

            SyndicationFeed currentFeed = null;

            var localStorage = new LocalStorage();
            currentFeed = await localStorage.Read_feed_from_disk();

            var uriString = Get_url();
            
            if (currentFeed == null)
            {
                
                var uri =
                    new Uri(
                        uriString);

                var client = new SyndicationClient {BypassCacheOnRetrieve = true};
                // Some servers require a user-agent
                client.SetRequestHeader("user-agent",
                                        "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

                currentFeed = await client.RetrieveFeedAsync(uri);
                localStorage.Write_feed_to_disk(currentFeed);
            }

            var itemCollection = new List<Item>();
            for (int i = 0; i < currentFeed.Items.Count; i++)
            {
                SyndicationItem syndicationItem = currentFeed.Items[i];
                var item = new Item { Title = syndicationItem.Title.Text, PublishedDate = syndicationItem.PublishedDate.ToString("dd/MM/yyyy") };

                if (syndicationItem.Summary != null) item.Content = HtmlUtilities.ConvertToText(syndicationItem.Summary.ToString());

                if (syndicationItem.Links != null) item.Link = syndicationItem.Links[0].Uri.ToString();
                itemCollection.Add(item);
            }

            return itemCollection;
        }

        public string Get_url()
        {
            var url = localSettings.Get_value(urlKey);
            string uriString =
                    "http://www.google.com/reader/public/atom/user%2F10937322286897482447%2Fbundle%2FZubair%27s%20Feed%20Bundle";
            //string uriString = "http://blogs.msdn.com/b/b8/rss.aspx";
            if (url != null) uriString = url.ToString();

            return uriString;
        }

        public void Put_url(string url)
        {
            localSettings.Store_value(urlKey,url);
        }

        public void Delete_url()
        {
            localSettings.Remove_setting(urlKey);
        }
    }
}
